package com.github.permissiondog.cancanpbackend.servlet;

import com.alibaba.excel.EasyExcel;
import com.github.permissiondog.cancanpbackend.model.ExportData;
import com.github.permissiondog.cancanpbackend.request.ApproveApplicationRequest;
import com.github.permissiondog.cancanpbackend.response.ApplicationsResponse;
import com.github.permissiondog.cancanpbackend.response.BaseResponse;
import com.github.permissiondog.cancanpbackend.response.ProgressResponse;
import com.github.permissiondog.cancanpbackend.service.ApplicationService;
import com.github.permissiondog.cancanpbackend.service.TemplateService;
import com.github.permissiondog.cancanpbackend.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.format.DateTimeFormatter;

@WebServlet("/approver/application/export")
public class ApproverApplicationExportServlet extends BaseServlet {
    /**
     * 导出已审批列表
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            var apps = ApplicationService.getInstance().getApplicationsByApproverId(
                    userLoggedIn(req).getId()
            );
            var data = apps.stream().map(app -> {
                var ed = new ExportData();
                var applicant = UserService.getInstance().getUserById(app.getApplicantId());
                var template = TemplateService.getInstance().getTemplateById(app.getTemplateId());
                ed.setId(app.getId());
                ed.setApplicantNickname(applicant.getNickname());
                ed.setTemplateName(template.getTableName());
                ed.setCreationTime(app.getCreationTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                ed.setConfirmed(app.isConfirmed());
                return ed;
            }).toList();

            resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            resp.setCharacterEncoding("utf-8");

            var filename = "审批模板导出.xlsx";
            resp.setHeader("Content-disposition", "attachment;filename*=utf-8''" + filename);
            EasyExcel.write(resp.getOutputStream(), ExportData.class).sheet("审批表").doWrite(data);

        } catch (Exception e) {
            json(resp, BaseResponse.builder().ok(false).error(e.getMessage()).build());
        }
    }
}
